<?php

namespace Home\Controller;
use Think\Server;
use Think\Db;

header('content-type:text/html;charset=utf-8');
class WorkermanhundredController extends Server {

	protected $socket = 'websocket://0.0.0.0:15100';

	/*添加定时器
	 *监控连接状态
	 * */
	public function onWorkerStart(){
		$msg_data = array();
		$auth = auth_check(C('auth_code'),C('siteurl'));
		if (!$auth) {
			echo "未授权或授权已过期";exit;
		}

		/*结算*/
		$time_interval = 1;//定时一秒 即每秒触发一次
		\Workerman\Lib\Timer::add($time_interval, function(){
            //机器人
            $hundred = M('hundred')->where("type=0")->order("id desc")->find();
		    if ($hundred['status']==9){//1开启  9关闭
                $robot_t= robot_pinlv();//机器人频率
                $robot2=F('hundred');
                if ($robot2&&$robot2>0){
                    F('hundred',$robot2-1);
                }else {
                    if ($robot2 == 0) {//机器人启动
                        //机器人
                        $mess = $this->robot_message();
                        $robot = $this->robot();
                        $new_message = array(
                            'type' => 'say',
                            'head_img_url'=>'/Uploads'.$robot[0]['headimgurl'],
                            'from_client_name' => $robot[0]['nickname'],
                            'content'=>$mess,
                            'time'=>date('H:i:s')
                        );
                        foreach ($this->worker->uidConnections as $con) {
                            $con -> send(json_encode($new_message));
                        }
//                        $this -> send(json_encode($new_message));
                        $this->add_message($new_message);

                        F('hundred',$robot_t+rand(-3,3));
                    }
                }

//                $this->add_message($new_message);
            }



			//获取当前和上期 数据
			$hundred_info = M('hundred')->where("type=0")->order("id desc")->limit(2)->select();
			//触发结算操作结算上一期 上一期未结算且有结果 当前未结算无结果
			if($hundred_info[1]['status'] == '2' && $hundred_info[1]['award_numbers'] != '0' && $hundred_info[0]['award_numbers'] == '0'){
				//结算
				//开奖结果
				$period_number = $hundred_info[1]['period_number'];
                //本期得奖方法集
                $award_int = explode(',',$hundred_info[1]['award_int']);
//				$result_code = M('hundred')->field("award_numbers")->where("period_number='$period_number'")->find();
				//转成数组 方便使用
				$res_code = explode(',',$hundred_info[1]['award_numbers']);
				//当前局所有竞猜
				$list = M('order')->where("number = '$period_number' and state = 1 and is_add = 0 and game='hundred'")->order("time ASC")->select();
				if($list){
                    $quzc_z=0;$quzc_x=0;//去占成的
					foreach($list as $k=>$v){
						$id = $list[$k]['id'];
						$userid = $list[$k]['userid'];
						//给上级返现 并添加记录(ok)
						if($list[$k]['t_id'] and C('fenxiao_set') == 2){
							M('user')->where("id = {$list[$k]['t_id']}")->setInc('yong', $list[$k]['del_points']*C('fenxiao')*0.01);
							M('user')->where("id = {$list[$k]['t_id']}")->setInc('t_add', $list[$k]['del_points']*C('fenxiao')*0.01);
							$fx_data = array(
								'uid' => $userid,
								't_uid' => $list[$k]['t_id'],
								'orderid' => $id,
								'push_money' => $list[$k]['del_points'],
								'rate' => C('fenxiao')*0.01,
								'money' => $list[$k]['del_points']*C('fenxiao')*0.01,
								'time' => time()
							);
							M('push_money')->add($fx_data);
						}

						//结算1：判断是否中奖$award_int
                        $user_add_point=0;
                        if(in_array($v['jincai_zl'],$award_int)){
                            //结算2：不同中奖不同解决
                            echo'有中奖';
                            switch($v['jincai_zl']){
                                case '1'://庄
                                    $user_add_point += $v['del_points'] * C('hundred_z_point');
                                break;
                                case '2'://闲
                                    $user_add_point += $v['del_points'] * C('hundred_x_point');
                                    break;
                                case '3'://和
                                    $user_add_point += $v['del_points'] * C('hundred_h_point');
                                    break;
                                case '4'://庄对
                                    $user_add_point += $v['del_points'] * C('hundred_zxd_point');
                                    break;
                                case '5'://闲对
                                    $user_add_point += $v['del_points'] * C('hundred_zxd_point');
                                    break;
                                case '6'://对子
                                    if (in_array(4,$award_int)){//有庄对
                                        $user_add_point += $v['del_points']/2 * C('hundred_zxd_point');
                                    }
                                    if (in_array(5,$award_int)){//有闲对
                                        $user_add_point += $v['del_points']/2 * C('hundred_zxd_point');
                                    }
                                    break;
                                case '7'://三宝
                                    if (in_array(3,$award_int)){//有和
                                        $user_add_point += $v['del_points']/3 * C('hundred_h_point');
                                    }
                                    if (in_array(4,$award_int)){//有庄对
                                        $user_add_point += $v['del_points']/3 * C('hundred_zxd_point');
                                    }
                                    if (in_array(5,$award_int)){//有闲对
                                        $user_add_point += $v['del_points']/3 * C('hundred_zxd_point');
                                    }

                                    break;
                                default:
                            }
                        }
                        //记录吃码量（对冲（实） 不足吃码量的部分）
                        switch($v['jincai_zl']) {
                            case '1'://庄
                                $quzc_z += $v['quzc_points'];
                                break;
                            case '2'://闲
                                $quzc_x += $v['quzc_points'];
                                break;
                        }

                        //修改用户表以及订单表的相关数据
                        $order_id = $v['id'];
                        $user_id = $v['userid'];
                        //修改order和user 发放中奖金额
                        $this->add_points($order_id,$user_id,$user_add_point);
                        $this->send_msg('pointsadd',$user_add_point,$user_id);

					}

                   //去占成庄闲对冲
                    if ($quzc_z>$quzc_x){
                        $quzc_zx='庄';
                        $quzc_dc=$quzc_z-$quzc_x;
                    }elseif($quzc_z<$quzc_x){
                        $quzc_zx='闲';
                        $quzc_dc=$quzc_x-$quzc_z;
                    }else{
                        $quzc_dc=0;
                    }

                    if ($quzc_dc>0){//计算吃码后的值 （吃码量的倍数  多的不计）
                        if ($quzc_dc>=C('chima')){
                            $vv=$quzc_dc%C('chima');
                            $vv=$quzc_zx.'/'.$vv;
                            M("hundred")->where(['id'=>$hundred_info[1]['id']])->save(['chima'=>$vv]);
                        }
                    }
        //推送实时变更的筹码  （实时码量）
                    $zhuang=0;//庄总计
                    $xian=0;//闲总计
                    foreach ($list as $k=>$v){
                        $xiazhu=json_decode($v['jincai'],true);
                        $xiazhu_class=array_keys($xiazhu)[0];
                        $xiazhu_val=array_values($xiazhu)[0];
                        if ('庄'==$xiazhu_class){
                            $zhuang+=$xiazhu_val;
                        }else if('闲'==$xiazhu_class){
                            $xian+=$xiazhu_val;
                        }
                    }
                    $zx=$zhuang-$xian;//庄闲对冲
                    $bet_points=0;//增减码量
                    $res_code = explode(',',$hundred_info[1]['award_numbers']);
                    $bet_points =$zx;
                    if ('庄'==$res_code[0]){//开庄
//                        $bet_points*=1;//庄+
                        if ($zx>0) {//庄多
                            $bet_points = $zx * (C('hundred_z_point') - 1);
                        }
                    }
                    else if ('闲'==$res_code[0]){//开闲
                        if ($zx>0) {//庄多
                            $bet_points = $zx*-1;
                        }else{
                            $bet_points=$zx * (C('hundred_x_point')-1)*-1;
                        }
                    }
                    else{
                        $bet_points=0;
                    }

                    $bet_points=(int)$bet_points;
                    $conf = M("hundred_config")->where("type=0")->field("id,has_points")->order("id desc")->find();
                    $conf_id = $conf['id'];

                    M("hundred_config")->where("id=$conf_id")->setInc("has_points",$bet_points);
				}

			}
    	});
		
		//系统公告(ready)
		\Workerman\Lib\Timer::add(100, function(){
			$new_message = array(
				'type' => 'system',
				'code' => '200',
//                'head_img_url'=>'/Public/main/img/system.jpg',
                'head_img_url'=>'/Uploads/'.kefuurl(),

				'from_client_name' => '客服',
                'content'=>'由于各地网络情况不同，开奖视频存在延迟，请点击视频右下方刷新视频！',
				'time'=>date('H:i:s')
			);
			foreach ($this->worker->connections as $conn) {

				$conn -> send(json_encode($new_message));
			}
			
    	});

	}
	
	/*
	 * 客户端连接时
	 * 
	 * */
	public function onConnect($connection){
		$connection->onWebSocketConnect = function($connection , $http_header)
		{

		};
	}
	
	/**
	 * onMessage
	 * @access public
	 * 转发客户端消息
	 * @param  void
	 * @param  void
	 * @return void
	 */
	public function onMessage($connection, $data) {
		$user = session('user');
		// 客户端传递的是json数据
		$message_data = json_decode($data, true);
		if (!$message_data) {
			return;
		}
				
		// 1:表示执行登陆操作 2:表示执行说话操作 3:表示执行退出操作
		// 根据类型执行不同的业务
		switch($message_data['type']){
			// 客户端回应服务端的心跳
			case 'pong' :
				// $connection -> send("success");
				break;
			case 'login' :
				// 把昵称放到session中
				$client_name = htmlspecialchars($message_data['client_name']);
				
				/* 保存uid到connection的映射，这样可以方便的通过uid查找connection，
		        * 实现针对特定uid推送数据
		        */
				$connection->uid = $message_data['client_id'];
				$this->worker->uidConnections[$connection->uid] = $connection;
				
				//session($connection->uid,$client_name);

				$new_message = array(
					'type' => 'admin',
					'code' => '200',
					'head_img_url'=> '/Uploads/'.kefuurl(),
					'from_client_name' => 'GM管理员',
					'content' => C('welcome'), 
					'time' => date('H:i:s')
				);
				$connection -> send(json_encode($new_message));
				break;	
			case 'say' :
				//type   say
				//number 期号
				//game   hundred
				//content 竞猜的参数
				$userid = $connection->uid;
				/*是否竞猜时间*/
				$year = date("Ymd",time());
				$begin_today = strtotime($year.C('hundred_start_time'));//1天开始时间
				$end_today = strtotime($year.C('hundred_stop_time'));//一天结束时间
				$l_time = time();				
				if($l_time > $end_today || $l_time < $begin_today || C('hundred_is_open') == '0'){//非竞猜时间
					$time_error_message = array(
						'uid'  => $connection->uid,
						'type' => 'say',
						'code' => '400',
						'head_img_url'=>$message_data['headimgurl'],
						'from_client_name' => $message_data['client_name'],
						'content' => $message_data['content'], 
						'time' => date('H:i:s')
					);

					$connection -> send(json_encode($time_error_message));
					$time_error_message['type'] = 'say_error'; 
					$this->add_message($time_error_message);/*添加信息*/
					
					$time_message = array(
						'uid'  => $connection->uid,
						'type' => 'admin',
						'code' => '400',
						'head_img_url'=> '/Uploads/'.kefuurl(),
						'from_client_name' => 'GM管理员',
						'content' => $message_data['content'].'非竞猜时间，竞猜失败', 
						'time' => date('H:i:s')
					);
					// $msg_data = array(
					// 	'code' => '402',
					// 	'msg'  => '非竞猜时间，竞猜失败',
					// 	'content' => $time_message
					// );					
					$connection -> send(json_encode($time_message));
					$time_message['type'] = 'error';
					$this->add_message($time_message);/*添加信息*/
				}
				else{
					//检查投注时间 和 当前期数
					$time = time();
					$where=['open_time'=>['LT',$time],'type'=>'0',];
//					$where = "open_time < '{$time}' and type='0'";
					$now = M('hundred')->where($where)->order("id desc")->limit("1")->select();
					if($now[0]['status'] == '1'){
						/*检测格式和金额*/
						$money_data = $message_data['content'];
                        $sh=array_keys($money_data);

                        $jingcai_zi=0;
//                        $cx='撤庄 CZ 撤闲 CX 撤和 CH 撤对子 CDZ 撤庄对 CZD 撤闲对 CXD 撤三宝 CSB';//撤销命令
                        $qc=array('撤','C','全撤','QC',);
                        $cx=array('撤庄','CZ','撤闲','CX','撤和','CH','撤对子','CDZ','撤庄对','CZD','撤闲对','CXD','撤三宝','CSB');
                        if (in_array($sh[0],$qc)){//撤注单系列-全撤
                            M()->startTrans();
                            try {
                                //删除该玩家本期所有的投注
                                $user_id = $userid;
                                $where_zq=['number'=>$now[0]['period_number'],
                                    'userid'=>$userid,
                                    'game'=>'hundred'];
                                $msg='全撤成功';
                                $del_points= M('order')->where($where_zq)->sum('del_points');
                                if (0==$del_points){$msg='无可撤注单';}else{
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();
                                    M()->commit();
                                }
                                $new_message2 = array(
                                    'uid'  => $connection->uid,
                                    'type' => 'admin',
                                    'code' => '200',
                                    'head_img_url'=> '/Uploads/'.kefuurl(),
                                    'from_client_name' => 'GM管理员',
                                    'content' =>  $msg,
                                    'time' => date('H:i:s')
                                );
                                $connection -> send(json_encode($new_message2));
                            } catch (Exception $e) {
                                M()->rollback();
                            }
                            return;
                        }
                        else if(in_array($sh[0],$cx)){//撤注单系列-单撤
                            $where_zq=['number'=>$now[0]['period_number'],
                                'userid'=>$userid,
                                'game'=>'hundred'];
                            $msg=$sh[0];
                            if ('撤庄'==$sh[0]||'CZ'==$sh[0]){
                                $msg='撤庄';
                                $where_zq['jincai_zl']=1;
                            }elseif('撤闲'==$sh[0]||'CX'==$sh[0]){
                                $msg='撤闲';
                                $where_zq['jincai_zl']=2;
                            }elseif('撤和'==$sh[0]||'CH'==$sh[0]){
                                $msg='撤和';
                                $where_zq['jincai_zl']=3;
                            }elseif('撤庄对'==$sh[0]||'CZD'==$sh[0]){
                                $msg='撤庄对';
                                $where_zq['jincai_zl']=4;
                            }elseif('撤闲对'==$sh[0]||'CXD'==$sh[0]){
                                $msg='撤闲对';
                                $where_zq['jincai_zl']=5;
                            }elseif('撤对子'==$sh[0]||'CDZ'==$sh[0]){
                                $msg='撤对子';
                                $where_zq['jincai_zl']=6;
                            }elseif('撤三宝'==$sh[0]||'CSB'==$sh[0]){
                                $msg='撤三宝';
                                $where_zq['jincai_zl']=7;
                            }
                            M()->startTrans();
                            try {
                                //删除该玩家本期所有的投注
                                $user_id = $userid;

                                $del_points= M('order')->where($where_zq)->sum('del_points');
                                if (0==$del_points){$msg=$msg.'失败，没有下注';}else{
                                    $msg= $msg.'成功';
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();
                                    M()->commit();
                                }

                                //GM管理员发给个人的竞猜通知
                                $new_message2 = array(
                                    'uid'  => $connection->uid,
                                    'type' => 'admin',
                                    'code' => '200',
                                    'head_img_url'=> '/Uploads/'.kefuurl(),
                                    'from_client_name' => 'GM管理员',
                                    'content' =>  $msg,
                                    'time' => date('H:i:s')
                                );
                                $connection -> send(json_encode($new_message2));
                            } catch (Exception $e) {
                                M()->rollback();
                            }
                            return;
                        }
                        $user_info = M("user")->field("id,points,nickname,username,t_id")->where("id='$userid' and status=1")->find();
                        if (stristr($sh[0],'梭哈')){//梭哈系列
                            echo '梭哈';
                            //查询余额
                            $user_points=(int)$user_info['points'];
                            $sh_xilie=array('梭哈庄','梭哈闲','梭哈和','梭哈庄对','梭哈闲对',/*'梭哈对子','梭哈三宝',*/);//梭哈系列
                            $isin = array_search($sh_xilie,$sh[0]);//在数组中搜索键值 $a，并返回它的键名：
                            $xiazhu= xiazhu_daima($sh[0]);
                            $xiazhu2=jingcai_zi_fanyi($xiazhu);
                            $money_data=[$xiazhu2=>$user_points];
                            $jingcai_zi=$xiazhu;
                        }
                        elseif('对子'==$sh[0]){//对子*2
                            $xiazhu= xiazhu_daima($sh[0]);
                            $xiazhu2=jingcai_zi_fanyi($xiazhu);
                            $money_data=[$xiazhu2=>(int)$money_data[$sh[0]]*2];
                            $jingcai_zi=$xiazhu;
                        }
                        elseif('三宝'==$sh[0]){//三宝*3
                            echo '是三宝';
                            $xiazhu= xiazhu_daima($sh[0]);
                            $xiazhu2=jingcai_zi_fanyi($xiazhu);
                            $money_data=[$xiazhu2=>(int)$money_data[$sh[0]]*3];
                            $jingcai_zi=$xiazhu;
                        };

//                        elseif('对子'==$sh[0]){
//
//                            $money_data=[$xiazhu2=>$user_points];
//                            $jingcai_zi=$xiazhu;
//                        }
//                        $this->send_msg('pointsadd',500,$userid);//弹窗通知
//                        return;
						$res = $this->checkHundredMoney($userid,$money_data,$now[0]['period_number']);

						if($res['code']== '0'){
                            $all_money = array_sum($money_data);
                            $message=[
                                'uid'=>$connection->uid,
                                'type' => 'admin',
                                'head_img_url'=> '/Uploads/'.kefuurl(),
                                'from_client_name' => 'GM管理员',
                                'code' => '400',
//								'head_img_url'=> $message_data['headimgurl'],
//								'from_client_name' => $message_data['client_name'],
                                'content' => $all_money,
                                'time' => date('H:i:s')
                            ];
                            $connection -> send(json_encode($message));
							$error_message = array(
								'uid'=>$connection->uid,
								'type' => 'admin',
								'head_img_url'=> '/Uploads/'.kefuurl(),
								'from_client_name' => 'GM管理员',
								'code' => '400',
//								'head_img_url'=> $message_data['headimgurl'],
//								'from_client_name' => $message_data['client_name'],
								'content' => $res['content'], 
								'time' => date('H:i:s')
							);
							// $msg_data = array(
							// 	'code' => '401',
							// 	'msg'  => $res['content'],
							// 	'content' => $error_message
							// );
							$connection -> send(json_encode($error_message));
							$error_message['type'] = 'say_error';
							$this->add_message($error_message);/*添加信息*/
						}
						else if($res['code'] == '1'){
							$map['userid'] = $userid;
							$map['state'] = 1;
							$map['is_add'] = 0;
							$map['time'] = time();
							$map['number'] = $now[0]['period_number'];
							$map['jincai_zl'] =$res['jincai_zl'];
							$map['jincai'] = json_encode($message_data['content'],JSON_UNESCAPED_UNICODE);
							$map['del_points'] = $res['all_money'];
							$map['balance'] = $res['points']-$res['all_money'];
							$map['nickname'] = $res['nickname'];
							$map['username'] = $res['username'];
							$map['game'] = 'hundred';
							$map['t_id'] = $res['t_id'];
                            $quzc_points=$map['del_points'];
                            if ($map['jincai_zl']==1||$map['jincai_zl']==2){//庄/闲去占成
                                $user=M('user')->find($connection->uid);
                                $t_id=$user['t_id'];
                                if ($t_id>0){//查看代理占成
                                    $t_user=M('user')->where(['id'=>$t_id,'is_agent'=>1])->find();
                                    if ($t_user&&$t_user['zhancheng']>0){
                                        $quzc_points=$map['del_points']*(1-($t_user['zhancheng']/100));
                                    }
                                }
                            }
                            $map['quzc_points']=$quzc_points;//去占成后的投注
//                            var_dump($del_points);return;
							/*添加竞猜*/
							if(!$res['is_robot']) {
								M()->startTrans();
								try {
                                    //删除之前的投注
                                    //1.找到该用户本期之前的相同投注
                                    $user_id = $userid;
                                    $where_zq=['number'=>$map['number'],
                                        'jincai_zl'=>$map['jincai_zl'],
                                        'game'=>$map['game']];
                                    $del_points= M('order')->where($where_zq)->sum('del_points');
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();

									/*减分*//*添加竞猜*/
									M('order')->add($map);
									M('user')->where("id = $userid")->setDec('points', $map['del_points']);
									M()->commit();
								} catch (Exception $e) {
									M()->rollback();
								}


								//变更的筹码
//								$conf = M("hundred_config")->field("id,has_points")->order("id desc")->find();
//								$conf_id = $conf['id'];
//								M("hundred_config")->where("id='$conf_id'")->setDec("has_points", $map['del_points']);
//								$has_points = $conf['has_points']-$map['del_points'];
//								$this->send_fen($content=array('has_points'=>$has_points));
							}
							/*成功通知*/
							$jincai_data = json_decode($map['jincai'],true);
							$jincai_keys = array_keys($jincai_data);
//							$jincai = $jincai_str.':'.$jincai_num;
							foreach($jincai_keys as $k=>$v){
							    //竞猜成功通知1：GM管理员发给个人的竞猜通知
								$new_message2 = array(
									'uid'  => $connection->uid,
									'type' => 'admin',
									'code' => '200',
									'head_img_url'=>'/Uploads/'.kefuurl(),
									'from_client_name' => 'GM管理员',
									'content' =>  '「'.$v.'/'.$jincai_data[$v].'」'.',竞猜成功',
									'time' => date('H:i:s')
								);
								$connection -> send(json_encode($new_message2));
//								$this->add_message($new_message2);/*添加信息*/
                                //竞猜成功通知2：个人发到整个房间（同代理）的竞猜
								$new_message3 = array(
									'type' => 'say',
									'head_img_url'=> $message_data['headimgurl'],
									'from_client_name' => $message_data['client_name'],
									'content' => $v.'/'.$jincai_data[$v],
									'time' => date('H:i:s'),
									'uid' => $map['t_id'],
								);
								$this->add_message($new_message3);/*添加信息*/
								$new_message4 = array(
									'type' => 'say',
									'head_img_url'=> $message_data['headimgurl'],
									'from_client_name' => $message_data['client_name'],
									'content' => $v.'/'.$jincai_data[$v],
									'time' => date('H:i:s')
								);
								// //向全体发送消息
								// foreach ($this->worker->connections as $conn) {
								// 	$conn -> send(json_encode($new_message4));
								// }
								$point = 0-$jincai_data[$v];
                                //竞猜成功通知3：給个人的弹窗
								$this->send_msg('pointsadd',$point,$userid);
								//查询上级代理id
								$agent_info = M("user")->field("t_id")->where("id='$userid'")->find();
								if($agent_info['t_id'] == '0'){
									$agent_id = '0';
								}else{
									$agent_id = $agent_info['t_id'];
								}
                                 //向全体发送消息
                                 foreach ($this->worker->connections as $conn) {
                                 	$conn -> send(json_encode($new_message4));
                                 }
//                                $this->broadcast($new_message4);
//								$next_users = M("user")->field("id")->where("t_id='$agent_id'")->select();
//								foreach ($next_users as $k=>$v){
//									$userid = $next_users[$k]['id'];
//									if(isset($this->worker->uidConnections[$userid])){
//										$connection = $this->worker->uidConnections[$userid];
//										$connection->send(json_encode($new_message4));
//                                }
//								}
							}
						}
					}
					else{
						$msg_data = array(
							'uid'  => $connection->uid,
							'type' => 'admin',
							'code' => '400',
//                            'head_img_url'=>'/Public/main/img/kefu.jpg',
                            'head_img_url'=> '/Uploads/'.kefuurl(),
							'from_client_name' => 'GM管理员',
							'msg'  => '不在投注时间内',
							'content' => '不在投注时间内',
							'time' => date('H:i:s'),
							'status' => $now[0]['status'],
						);
						$connection -> send(json_encode($msg_data));

					}
				}
				break;

            case 'admin':
                $new_message = array(
                    'type' => 'admin',
                    'code' => '200',
                    'head_img_url'=> '/Uploads/'.kefuurl(),
                    'from_client_name' => 'GM管理员',
                    'content' => C('welcome'),
                    'time' => date('H:i:s')
                );
                break;
		}
	}
	
	
	public function robot_message(){
        $xiazhu=['庄','闲','和','庄对','闲对'];
		$xiazhu=$xiazhu[array_rand($xiazhu)];
		if($xiazhu=="庄"||$xiazhu=="闲"){
			$jiner=[2,500];//最小，最大,
		}else{
			$jiner=[1,200];//最小，最大,
		}
//        range(10,3000,10);//最小，最大,间隔

        $data=$xiazhu.'/'.rand($jiner[0],$jiner[1])*10;
		return $data;
	}

	public function robot(){
		$count = M('robot')->count();
     	$rand = mt_rand(0,$count-1); //产生随机数。
     	$limit = $rand.','.'1'; 
    	$data = M('robot')->limit($limit)->select();
		return $data;
	}

// 向所有验证的用户推送数据
    function broadcast($message)
    {
        $worker=$this->worker;
//        global $worker;
        foreach($worker->uidConnections as $connection)
        {
            $connection->send($message);
        }
    }
	/**
	 * onClose
	 * 关闭连接
	 * @access public
	 * @param  void
	 * @return void
	 */
	public function onClose($connection) {
		$user = session($connection->id);
		foreach ($this->worker->uidConnections as $con) {
			if (!empty($user)) {
				$new_message = array(
					'type' => 'logout',
					'from_client_name' => $user,
					'time' => date('H:i:s')
				);
				$con -> send(json_encode($new_message));
			}
		}
		
		if(isset($connection->uid)){
	        // 连接断开时删除映射
	        unset($this->worker->uidConnections[$connection->uid]);
    	}
	}
	
	
	/*存竞猜记录和信息*/
	protected function add_order($mew_message){
		$res = M('order')->add($mew_message);
		return $res;
	}
	protected function add_message($new_message){

		if (!empty($new_message)) {
			$new_message['game'] = 'hundred';
			$res = M('message')->add($new_message);
			return $res;
		}
	}
	
	
	/*
	 * 竞猜成功  加分
	 * */
	public function add_points($order_id,$userid,$points){
		M()->startTrans();
		try {
			M('user')->where("id = $userid")->setInc('points',$points);
            $user_points= $this->user_points($userid);
            M('order')->where("id = $order_id")->setField(array('is_add'=>'1','add_points'=>$points,'balance'=>$user_points));
			M()->commit();
		} catch (Exception $e) {
			M()->rollback();
		}
	}
	
	/*竞猜成功通知
	 * */
	public function send_msg($type,$points,$userid){
		$message_points = array(
			'type' => $type,
			'points'=>	$points,
			'userid' =>$userid,
			'time'=>date('H:i:s')
		);
		if(isset($this->worker->uidConnections[$userid])){
	        $connection = $this->worker->uidConnections[$userid];
	        $connection->send(json_encode($message_points));
	    }
	} 

	/*核对投注钱数
	 * userid 用户id
	 * moneyData 投注金额的数组
	 * */	
	public function checkHundredMoney($userid,$money_data,$number){
		$res = array();
		//查询该用户的金额是否能够投注
		$user_info = M("user")->field("id,points,nickname,username,t_id")->where("id='$userid' and status=1")->find();
		$all_money = array_sum($money_data); //投注的总钱数
		//查询之前的投注总额
        $before = M("order")->field("del_points,jincai")->where("userid='$userid' and is_add=0 and number='$number'")->select();
        $zong_del_points = M("order")->where("userid='$userid' and is_add=0 and number='$number'")->sum('del_points');
		if($all_money > C('hundred_min_money') && $all_money < C('hundred_max_money')){
			if($all_money <= $user_info['points']){
				$zong = $zong_del_points;
                $z=0;
                $x=0;

				$bet = json_decode($money_data,true);
				$bet_key = array_keys($money_data);
				/*$aa=[
                    ['对子',C('hundred_dz_money')],
                    ['三宝',C('hundred_sb_money')],
                    ['和',C('hundred_h_money')],
                    ['庄对',C('hundred_zxd_money')],
                    ['闲对',C('hundred_zxd_money')],
                    ['庄',C('hundred_z_money')],
                    ['闲',C('hundred_x_money')],
                ];
				foreach ($aa as $v){
                    if ($v[0]==$bet_key[0]){
                        $bet_money = $all_money;
                        if($bet_money >$v[1]){
                            $res['code'] = "0";
                            $res['content'] = $v[0]."超出限额";
                            return $res;
                        }
                    }
                }*/

				if ('对子'==$bet_key[0]){
                    $bet_money = $all_money;
                    if($bet_money > C('hundred_dz_money')){
                        $res['code'] = "0";
                        $res['content'] = "对子超出限额";
                        return $res;
                    }
                    //余额够不够
//                    all_money
                }
				elseif('三宝'== $bet_key[0] ){
                    $bet_money = $all_money;
                    if($bet_money > C('hundred_sb_money')){
                        $res['code'] = "0";
                        $res['content'] = "三宝超出限额";
                        return $res;
                    }
                }
				elseif($bet_key[0] == '和'){
					$bet_money = $all_money;
					if($bet_money > C('hundred_h_money')){
						$res['code'] = "0";
						$res['content'] = "和超出限额";
						return $res;
					}
				}
				else if($bet_key[0] == '庄对' ){
					$bet_money = $all_money;
					if($bet_money > C('hundred_zxd_money')){
						$res['code'] = "0";
						$res['content'] = "庄对超出限额";
						return $res;
					}
				}
				elseif( $bet_key[0] == '闲对'){
                    $bet_money = $all_money;
                    if($bet_money > C('hundred_zxd_money')){
                        $res['code'] = "0";
                        $res['content'] = "闲对超出限额";
                        return $res;
                    }
                }
				else if($bet_key[0] == '庄'){

                    $bet_money = $all_money;
                    if($bet_money > C('hundred_z_money')){
                        $res['code'] = "0";
                        $res['content'] = "庄超出限额";
                        return $res;
                    }

                }
				else if($bet_key[0] == '闲'){
                    $bet_money = $all_money;
                    if($bet_money > C('hundred_x_money')){
                        $res['code'] = "0";
                        $res['content'] = "闲超出限额";
                        return $res;
                    }
                }
				else{
                    $res['code'] = "0";
                    $res['content'] = "不支持该投注";
                    return $res;
                }
				//        之前总投+这注
				$bet_money = $zong + $all_money;
				if($bet_money > C('hundred_max_money')){
					$res['code'] = "0";
					$res['content'] = "投注超出最高限额";
					return $res;
				}
                $xiazhu= xiazhu_daima($bet_key[0]);
                $res['code'] = "1";
				$res['all_money'] = $all_money;
				$res['jincai_zl']=$xiazhu;
				$res['nickname'] = $user_info['nickname'];
				$res['username'] = $user_info['username'];
				$res['t_id'] = $user_info['t_id'];
				$res['points'] = $user_info['points'];
				$res['is_robot'] = $user_info['is_robot'];
			}
			else{
				$res['code'] = "0";
				$res['content'] = "账户金额不足";
			}
		}
		else if ($all_money<=C('hundred_min_money')){
			$res['code'] = "0";
			$res['content'] = "低于规则投注限额";
		}else if ($all_money>=C('hundred_min_money')){
            $res['code'] = "0";
            $res['content'] = "投注超出最高限额";
        }
		return $res;
	}

	protected function send_fen($content){
		// 指明给谁推送，为空表示向所有在线用户推送
		$to_uid = 0;
		// 推送的url地址，上线时改成自己的服务器地址
		$push_api_url = "http://localhost:12225/";
		$post_data = array(
			"type" => "publish",
			"content" => json_encode($content),
			"to" => $to_uid,
		);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
		curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
		$return = curl_exec ( $ch );
		curl_close ( $ch );
		return $return;
	}
	
}
?>